package org.track.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.track.web.entity.Status;
import org.track.web.entity.TrackRow;
import org.track.web.validator.TrackValidator;


/**
 * 
 * @author josdem (joseluis.delacruz@gmail.com)
 *
 */

@Controller
@RequestMapping("/register/*")
public class TrackController {
	private static final Log log = LogFactory.getLog(TrackController.class);

	@InitBinder("trackRow")
	public void initBinder(WebDataBinder binder) {
		log.debug("Validating data");
		binder.setValidator(new TrackValidator());
	}

	@RequestMapping
	public ModelMap showForm(ModelMap model) {
		log.debug("registering a new track");
		TrackRow track = new TrackRow();
		model.addAttribute(track);
		model.addAttribute(populateStatusList());
		return model;
	}

	@RequestMapping
	public Object addTrack(@Valid TrackRow trackRow, BindingResult result,
			ModelMap model) {

		if (result.hasErrors()) {
			log.debug("Error de validacion: " + result);
			return "/register/showForm";
		}

		log.debug("Processing track, data:");
		log.debug("Artist: " + trackRow.getArtist());
		log.debug("Title " + trackRow.getTitle());
		log.debug("Album " + trackRow.getAlbum());
		log.debug("TrackNumber: " + trackRow.getTrackNumber());
		log.debug("Length: " + trackRow.getLength());
		log.debug("Status: " + trackRow.getStatus());

		return model;
	}

	private List<Status> populateStatusList() {
		List<Status> statusList;
		statusList = new ArrayList<Status>();
		for (Status status : Status.values()) {
			statusList.add(status);
		}
		return statusList;
	}

}
